package com.my.lucky.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import com.my.lucky.entity.StockQueryRecord;
import com.my.lucky.entity.WencaiKeyword;
import com.my.lucky.model.Stock2;
import com.my.lucky.repository.StockQueryRecordRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

@Service
@Slf4j
public class StockAlertService {
    // 用于存储上一次的股票数据
    private final Map<Long, Map<String, Stock2>> previousStockData = new ConcurrentHashMap<>();
    @Autowired
    StockQueryRecordRepository stockQueryRecordRepository;

    /**
     * 创建简化版的 Stock2 对象，只包含代码、名称和价格
     *
     * @param stock 原始 Stock2 对象
     * @return 简化版的 Stock2 对象
     */
    private Stock2 createSimplifiedStock(Stock2 stock) {
        Stock2 simplified = new Stock2();
        simplified.setCode(stock.getCode());
        simplified.setName(stock.getName());
        simplified.setPrice(stock.getPrice());
        simplified.setType(stock.getType());
        return simplified;
    }

    /**
     * 检查股票变化并生成提示
     *
     * @param currentStocks 当前股票数据
     * @param focusStocks   关注的股票代码列表
     * @return 提示信息列表
     */
    public List<Stock2> generateAlerts(List<Stock2> currentStocks, Set<String> focusStocks, WencaiKeyword keyword) {
        List<Stock2> alerts = new ArrayList<>();
        LocalDateTime maxQueryTime = stockQueryRecordRepository.findMaxQueryTimeByWencaiKeywordId(keyword.getId());
        List<StockQueryRecord> records = new ArrayList<>();
        Map<String, List<StockQueryRecord>> collect = new HashMap<>();
        log.info("maxQueryTime:{}" + maxQueryTime);
        if (maxQueryTime != null) {
            records = stockQueryRecordRepository.findLatestRecordsByWencaiKeywordId(keyword.getId(), maxQueryTime);
            log.info("records:{}" + records.size());
            List<StockQueryRecord> secondLatestRecords = stockQueryRecordRepository.findSecondLatestRecordsByWencaiKeywordId(keyword.getId(), maxQueryTime, DateUtil.beginOfDay(new Date()).toLocalDateTime());
            log.info("secondLatestRecords:{}" + secondLatestRecords.size());
            collect = secondLatestRecords.stream().collect(Collectors.groupingBy(StockQueryRecord::getStockCode));
        }
        Map<String, Stock2> stringStock2Map = previousStockData.get(keyword.getId());
        if (stringStock2Map == null || stringStock2Map.size() == 0) {

            Map<String, Stock2> stockMap = new HashMap<>();
            for (StockQueryRecord record : records) {
                Stock2 stock = new Stock2();
                stock.setCode(record.getStockCode());
                stock.setName(record.getStockName());
                stock.setType(record.getType());
                stockMap.put(record.getStockCode(), stock);
            }
            if (records.size() != 0) {
                stringStock2Map = stockMap;
                previousStockData.put(keyword.getId(), stockMap);
            }
        }
        for (Stock2 currentStock : currentStocks) {
            String code = currentStock.getCode().substring(0, 6);
            currentStock.setCode(code);
            if (focusStocks.contains(code)) {//重点关注里的
                currentStock.setType(1);
                alerts.add(currentStock);
            } else {
                // 检查是否在关注列表中
                // log.info("stringStock2Map:" + stringStock2Map);
                if (stringStock2Map != null) {

                    Stock2 previousStock = stringStock2Map.get(code);
                    List<StockQueryRecord> stockQueryRecords = collect.get(code);

                    if (previousStock == null) {
                        if (CollUtil.isEmpty(stockQueryRecords)) {
                            // 没有--》有
                            currentStock.setType(2);
                        } else {
                            // 洗盘 有--？没有-->有
                            currentStock.setType(3);
                        }
                        alerts.add(currentStock);
                    } else {
                        if (!CollUtil.isEmpty(stockQueryRecords)) {
                            // 连续有3次
                            // 有-》有-》有
                            currentStock.setType(4);
                        } else {
                            //有-》有
                            currentStock.setType(0);
                        }
                        alerts.add(currentStock);
                    }
                } else {
                    currentStock.setType(2);
                    alerts.add(currentStock);
                }
            }

        }

        // 更新previousStockData
        Map<String, Stock2> newStockMap = new HashMap<>();
        for (Stock2 currentStock : currentStocks) {
            newStockMap.put(currentStock.getCode(), createSimplifiedStock(currentStock));
        }
        previousStockData.put(keyword.getId(), newStockMap);
        return alerts;
    }

    /**
     * 清除特定股票的历史数据
     */
    public void clearStockHistory(String code) {
        previousStockData.remove(code);
    }

    /**
     * 清除所有历史数据
     */
    public void clearAllHistory() {
        previousStockData.clear();
    }
} 